﻿/* 
 *  <copyright file="ModelCmp.cs" company="Wesley Jowitt">
 *  
 *  SobrietyEngine: Copyright (c) 2011 Wesley Jowitt
 *  
 *  This software is distributed under a software license.
 *   * As of the creation time of this file, the license in use is the Microsoft Permissive License (Ms-PL) 
 *    * The license can be viewed at:
 *     * License.Txt in the root folder of this project
 *      * http://sobrietyengine.codeplex.com/license
 *       * http://www.microsoft.com/opensource/licenses.mspx
 *       
 *  </copyright>
 *   */

using System;
using System.Collections.Generic;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using SobrietyEngine.Actor;
using SobrietyEngine.Common;
using Xclna.Xna.Animation;

namespace SobrietyEngine.Components.Graphic
{
    public class AnimatedMeshCmp: Base3DGraphic, SobrietyEngine.Components.IComponent
    {
        String modelAssetName;
        Model model;
        Matrix[] ModelBoneTransforms;

        ModelAnimator animator;
        AnimationController curController = null;
        Dictionary<String, AnimationController> controllers = new Dictionary<string, AnimationController>();
        Effect skinnedFx;
        String animEffectAsset;

        IOrientation Rotation;
        IPosition Position;
        IScale Scale;

        float rot = 0.0f;
        Vector3 scale = Vector3.One;
        Vector3 pos = new Vector3();

        public AnimatedMeshCmp()
            : base()
        {
        }

        public AnimatedMeshCmp(String modelName, String animEffect)
        {
            modelAssetName = modelName;
            animEffectAsset = animEffect;
        }

        public override void Remove()
        {
            base.Remove();
            animator.Enabled = false;
            animator.Dispose();
            curController.Enabled = false;
            curController.Dispose();
        }

        public override void Set(Parameters parms)
        {
            base.Set(parms);

            modelAssetName = parms.GetValueAs<String>("ModelName", "none");
            model = Actor.GameServices().AssetGameService.Load<Model>(modelAssetName);

            if(modelAssetName == "none" || model == null)
                Logging.Logger.Error(this, "Missing modelAssetName / model");            
        }

        public override List<ParameterDescription> GetParameterDescriptions()
        {
            List<ParameterDescription> p = base.GetParameterDescriptions();
            p.Add(new ParameterDescription("ModelName", "Model asset name", typeof(String), "none"));
            return p;
        }

        public void SetAnimation(String animName)
        {
            curController = controllers[animName];
        }

         override public Boolean InitComponent()
        {
            Rotation = Actor.Get<IOrientation>();

            Position = Actor.Get<IPosition>();
            if (Position == null)
                throw new Exception("Position required");

            Scale = Actor.Get<IScale>();

            // Copy any parent ModelBoneTransforms.

            model = Actor.GameServices().AssetGameService.Load<Model>(modelAssetName);

            ModelBoneTransforms = new Matrix[model.Bones.Count];
            model.CopyAbsoluteBoneTransformsTo(ModelBoneTransforms);

            skinnedFx = Actor.GameServices().AssetGameService.Load<Effect>(animEffectAsset);

            // Replace the old effects with your custom shader
            foreach (ModelMesh mesh in model.Meshes)
            {
                foreach (ModelMeshPart part in mesh.MeshParts)
                {
                    if (!(part.Effect is BasicEffect))
                        continue;

                    BasicEffect oldEffect = (BasicEffect)part.Effect;
                    Effect newEffect = skinnedFx.Clone();
                    newEffect.Parameters["Texture"].SetValue(oldEffect.Texture);

                    newEffect.Parameters["LightColor"].SetValue(new Vector4(0.3f, 0.3f, 0.3f, 1.0f));
                    newEffect.Parameters["AmbientLightColor"].SetValue(new Vector4(1.25f, 1.25f, 1.25f, 1.0f));
                    newEffect.Parameters["Shininess"].SetValue(0.6f);
                    newEffect.Parameters["SpecularPower"].SetValue(0.4f);

                    // newEffect.Parameters["View"].SetValue(view);
                    // newEffect.Parameters["Projection"].SetValue(projection);

                    part.Effect = newEffect;
                    oldEffect.Dispose();
                }
            }

            animator = new ModelAnimator(Actor.Game, model);

            foreach (ModelMesh mesh in model.Meshes)
            {
                foreach (Effect effect in mesh.Effects)
                {
                    if (effect is BasicEffect)
                    {
                        BasicEffect basic = (BasicEffect)effect;
                        //  basic.View = view;
                        // basic.Projection = projection;
                    }
                    else if (effect is BasicPaletteEffect)
                    {
                        BasicPaletteEffect palette = (BasicPaletteEffect)effect;
                        // palette.View = view;
                        // palette.Projection = projection;

                        // enable some lighting
                        palette.EnableDefaultLighting();
                        palette.DirectionalLight0.Direction = new Vector3(0, 0, 1);
                    }
                }
            }

            // Add this in LoadGraphicsContent
            foreach (AnimationInfo ai in animator.Animations.Values)
            {
                controllers[ai.Name.ToLower()] = new AnimationController(Actor.Game, ai);
               
            }        

            return true;
        }

        public override void UpdateGraphic(GameTime time)
        {
            if (Rotation != null)
                rot = Rotation.GetRadiansXY();

            if (Scale != null)
                scale = Scale.Scale;

            pos = Position.PositionV3;
            animator.World = Matrix.CreateScale(scale) *
                // ModelBoneTransforms[mesh.ParentBone.Index] *
                            Matrix.CreateRotationY(rot) *
                            Matrix.CreateTranslation(pos);

            if(curController != null)
                RunController(animator, curController);
        }

        private void RunController(ModelAnimator animator, AnimationController controller)
        {
            foreach (BonePose p in animator.BonePoses)
            {
                p.CurrentController = controller;
                p.CurrentBlendController = null;
            }
        }

        public override void Draw(ICamera _camera, Matrix _projection, Matrix _view, Matrix _world)
        {
            if (Visible == false)
                return;

            // Draw the model. A model can have multiple meshes, so loop.
            foreach (ModelMesh mesh in animator.Model.Meshes)
            {
                // This is where the mesh Orientation is set, as well 
                // as our camera and projection.
                foreach (Effect effect in mesh.Effects)
                {
                    if (effect is BasicEffect)
                    {
                        BasicEffect beffect = effect as BasicEffect;
                        beffect.EnableDefaultLighting();
                       
                        beffect.View = _view;
                        beffect.Projection = _projection;
                        //beffect.World = _world * world;
                    }
                    else if(effect.Name == skinnedFx.Name)
                    {

                        effect.Parameters["View"].SetValue(_view);
                        effect.Parameters["Projection"].SetValue(_projection);
                        //effect.Parameters["World"].SetValue(_world * world);
                    }
                }
                // Draw the mesh, using the effects set above.
                mesh.Draw();
            }
        }
    }
}